const { createLogger, format, transports } = require("winston");
const MySQLTransport = require("./mysql_transport");

// 读取 config/config.json 数据库配置文件
// 根据环境变量 NODE_ENV 来选择对应数据库配置
const env = process.env.NODE_ENV || "development";

const config = require(__dirname + "/../config/config.json")[env];

const options = {
  host: config.host,
  user: config.username,
  password: config.password,
  database: config.database,
  port: config.port / 1,
  table: "VisitLogs",
};

const fieldsOptions = {
  ip: "ip",
  path: "path",
  query: "query",
  body: "body",
  userAgent: "userAgent",
  level: "level",
  meta: "meta",
  message: "message",
  timestamp: "timestamp",
  route: "route",
  method: "method",
  originName: "originName",
  user: "user",
};

const logger = createLogger({
  level: "info",
  format: format.combine(
    format.errors({ stack: true }), // 添加错误堆栈信息
    format.json()
  ),
  defaultMeta: { service: "stacking-machine-robotic-arm-api-service" },
  transports: [
    new MySQLTransport({
      ...options,
      fields: {
        ...fieldsOptions,
      },
    }), // 将日志写入数据库
  ],
});
if (process.env.NODE_ENV !== "production") {
  logger.add(
    new transports.Console({
      format: format.combine(
        format.colorize(), // 终端中输出彩色的日志信息
        format.simple()
      ),
    })
  );
}
// 添加一些实用的日志方法
const logInfo = (message, meta = {}) => {
  logger.info(message, { timestamp: new Date().toString(), ...meta });
};

const logError = (message, error, meta = {}) => {
  const errorObj = error instanceof Error ? error : null;
  logger.error(message, {
    timestamp: new Date().toString(),
    message: errorObj ? errorObj.message : error.message,
    stack: errorObj ? errorObj.stack : error.message,
    ...meta,
  });
};

const logWarn = (message, meta = {}) => {
  logger.warn(message, { timestamp: new Date().toString(), ...meta });
};

module.exports = {
  logger,
  logInfo,
  logError,
  logWarn,
};
// module.exports = logger;
